<template>
  <Layout>
    <PageHeader :class="getHeaderClass" title="签署流程" @back="() => router.go(-1)">
      <template #subTitle>
        <Steps v-model:current="currentSteps" :items="contractStepsList" />
      </template>
      <template #extra>
        <div :class="`${prefixCls}-right pr-2`">
          <a-button
            v-for="(item, index) in contractStepsList[currentSteps]?.headerTool || []"
            :key="index"
            v-bind="item"
          >
            {{ item.text }}
          </a-button>
        </div>
      </template>
    </PageHeader>

    <KeepAlive>
      <component :is="contractStepsList[currentSteps].content" />
    </KeepAlive>
  </Layout>
</template>

<script lang="ts" setup>
  import { useHeaderSetting } from '@/hooks/setting/useHeaderSetting';
  import { useAppInject } from '@/hooks/web/useAppInject';
  import { useDesign } from '@/hooks/web/useDesign';
  import { Layout, PageHeader, Steps, message } from 'ant-design-vue';
  import { computed, h, onMounted, ref, unref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import ContractForm from './components/ContractForm.vue';
  import ContractConsoleContext from './components/ContractConsoleContext.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { QrCode } from '@/components/Qrcode';
  import { EncryptionFactory } from '@/utils/cipher';
  import { PageEnum } from '@/enums/pageEnum';
  import { PDFViewContextProps, createPDFViewContext } from '../pdf-view/hooks/usePDFViewContext';
  import { pick } from 'lodash-es';
  import { ContractCanvasClass } from '../_core/useContractCanvas';
  import { getContractTemplateInfoApi } from '@/api/contract/template';
  import { addContractInfoApi, getContractInfoApi, updateContractInfoApi } from '@/api/contract';
  import { uploadApi } from '@/api/sys/upload';

  defineOptions({
    name: 'ContractConsole',
  });

  onMounted(async () => {
    if (route.query.temId) {
      await getContractTemplateInfoApi(route.query.temId).then(async (res) => {
        if (!res.id) {
          createErrorModal({
            title: '警告',
            content: '查不到该合同模板，请检查后重试',
          });
          return;
        }

        try {
          res.field = '[{"key":"name","label":"姓名","field":"doctorName"}]';

          contractPdfInfo.value = res;

          const formJSON = (
            typeof res.field == 'string' ? JSON.parse(res.field) : res.field
          ) as Array<Record<string, any>>;

          bindMapKey.value = Object.fromEntries(formJSON.map((el) => [el.field, el.key]));
        } catch (error) {
          console.error(error);
        }
      });
    }

    if (route.params.id) {
      getContractInfoApi(route.params.id).then(async (res) => {
        // contractPdfInfo.value = res;
      });
    }
  });

  const route = useRoute();
  const router = useRouter();
  const { prefixCls } = useDesign('layout-header');
  const { getIsMobile } = useAppInject();
  const { getHeaderTheme } = useHeaderSetting();

  const currentSteps = ref(0);
  const bindMapKey = ref({} as Record<string, string>);
  const contractPdfInfo = ref({} as PDFViewContextProps['contractPdfInfo']);

  const { state } = createPDFViewContext({
    // @ts-ignore
    contractClass: {} as ContractCanvasClass,
    contractPdfInfo,
    validateForm: async () => {},
  });
  const { createSuccessModal, createErrorModal } = useMessage();

  const contractStepsList = [
    {
      title: '设置文件与参与人',
      content: ContractForm,
      headerTool: [
        {
          text: '下一步',
          type: 'primary',
          iconSize: 18,
          async onClick() {
            await state.validateForm();
            currentSteps.value += 1;
          },
        },
      ],
    },
    {
      title: '设置签署位置并发起合同',
      content: ContractConsoleContext,
      disabled: true,
      headerTool: [
        {
          text: '下载文件',
          type: 'link',
          preIcon: 'ant-design:download-outlined',
          iconSize: 18,
          onClick() {
            const _contractClass = state.contractClass;
            _contractClass?.downloadFile();
          },
        },
        {
          text: '盖骑缝章',
          type: 'link',
          preIcon: 'icon-park-twotone:seal',
          iconSize: 18,
          async onClick() {
            const _contractClass = state.contractClass;
            console.log(_contractClass);
            if (!_contractClass) return;

            _contractClass.state.loading = true;
            await _contractClass.loadFile(import.meta.env.VITE_PUBLIC_PATH+'/src/assets/pdf/file/GF—2000—0801-scle.pdf');

            _contractClass.renderPage(
              _contractClass.contractCanvas[0],
              _contractClass.state.currentPage,
            );
          },
        },
        {
          text: '提交签署',
          type: 'primary',
          class: 'mx-6',
          onClick: handleSubmitSign,
        },
      ],
    },
  ];

  const getHeaderClass = computed(() => {
    const theme = unref(getHeaderTheme);
    return [
      prefixCls,
      {
        [`${prefixCls}--fixed`]: true,
        [`${prefixCls}--mobile`]: unref(getIsMobile),
        [`${prefixCls}--${theme}`]: theme,
      },
    ];
  });

  /** 提交签署 */
  async function handleSubmitSign() {
    const loading = message.loading('正在提交签署');

    try {
      const { contractClass } = state;

      console.log(contractClass.contractCanvas);
      console.log(bindMapKey.value);
      // console.log(contractClass.renderImg());
      const self_data = unref(bindMapKey);
      for (const key in self_data) {
        if (Object.prototype.hasOwnProperty.call(self_data, key)) {
          const element = self_data[key];
          self_data[key] = contractPdfInfo.value[element];
        }
      }

      const upload = await uploadApi({ file: await contractClass.renderImg().bold() }, () => {});
      self_data.pdfImg = upload.data.url;

      const self_api = self_data.id ? updateContractInfoApi : addContractInfoApi;
      const res = await self_api(self_data);

      if (!res.id) {
        createErrorModal;
        message.error('提交签署失败');
        return;
      }

      const encrypt = `${location.origin}${PageEnum.SIGN_H5_SUBMIT}/${res.id}`;

      /** 短信链接 */
      const APPID = 'wx43792dfe10bec5cc',
        APP_PATH = 'pages/common/webview/index';

      const smsStr = `weixin://dl/business/?appid=${APPID}&path=${APP_PATH}&query=url=${encrypt}&env_version=release`;
      console.log(smsStr);
      console.log(encrypt);

      createSuccessModal({
        title: '长按识别二维码签署合同',
        content: () => h('div', { class: 'ml-12' }, h(QrCode, { value: encrypt })),
      });
    } catch (error) {
      console.error(error);
    } finally {
      loading();
    }
  }
</script>

<style lang="less" scoped>
  @import url('@/layouts/default/header/index.less');

  ::v-deep(.ant-steps-item-icon) {
    line-height: 31px;
  }

  .ant-page-header {
    width: 100%;

    ::v-deep(&-heading) {
      padding-left: 30px;
      width: 100%;

      &-left {
        flex: 1;
      }

      &-sub-title {
        margin: 0 auto;
        width: 30%;
      }
    }
  }
</style>
